package lew.bing.exp.thi;

import java.util.BitSet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by 刘国兵 on 2018/9/8.
 */
public class TestThreadLocal {

    private ThreadLocal<Integer> local = new ThreadLocal<>(){
        @Override
        protected Integer initialValue() {
            return 1;
        }
    };

    public void getAndAdd() {
        Integer integer = local.get();
        System.out.println(Thread.currentThread().getName() + ": (get and add local) thread values is:"+integer);
        local.set(integer+1);
    }

    public void get() {
        System.out.println(Thread.currentThread().getName() + ": (get) local thread values is:"+local.get());
    }

    public void clear() {
        local.remove();
    }

    public static void main(String[] args) {
        ExecutorService service = Executors.newFixedThreadPool(4);
        final TestThreadLocal testThreadLocal = new TestThreadLocal();
        Runnable runnable = () -> {
          testThreadLocal.getAndAdd();
          testThreadLocal.get();
          testThreadLocal.clear();
        };
        service.submit(runnable);
        service.submit(runnable);
        service.submit(runnable);
        service.submit(runnable);
        service.submit(runnable);
        // 有时候数组下标可作为数据
    }

}
